package com.comtime.service;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;

import android.app.Notification;
import android.app.NotificationManager;
import android.app.Service;
import android.content.Intent;
import android.net.Uri;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.util.Log;
import android.widget.RemoteViews;

import com.comtime.manager.SKNotificationManager;
import com.comtime.smartkilimanjaro.R;
import com.comtime.utils.MySharedPreferences;

public class DownloadService extends Service {
	private String tag = "DownloadService";
	private NotificationManager mNotificationManager;
	Notification notification;
	private final int NOTIFY_ID = 6;
	private boolean canceled;
	private int progress;
	private String apkUrl  ;
	/* 下载包安装路径 */
	private final String savePath = "/sdcard/";
	private String saveFileName = "  ";

	@Override
	public IBinder onBind(Intent intent) {

		return null;
	}

	@Override
	public void onDestroy() {
		super.onDestroy();
		Log.e(tag, "hehe onDestroy");
	}

	@Override
	public int onStartCommand(Intent intent, int flags, int startId) {

		return super.onStartCommand(intent, flags, startId);
	}

	@SuppressWarnings("deprecation")
	@Override
	public void onCreate() {
		super.onCreate();
		Log.e(tag, "hehe onCreate ");
		String urlString = MySharedPreferences.getInstance(this).getAPKUrl();
		if (urlString != null && !urlString.equals("")) {
			apkUrl = urlString;
		}

		saveFileName = savePath + getString(R.string.app_name) + ".apk";
		Log.e(tag, "hehe onCreate");
		mNotificationManager = (NotificationManager) getSystemService(android.content.Context.NOTIFICATION_SERVICE);

		notification = new Notification(R.drawable.ic_launcher,
				getString(R.string.app_name) + getText(R.string.downloading),
				System.currentTimeMillis());
		//notification.flags = Notification.FLAG_ONGOING_EVENT;

		RemoteViews contentView = new RemoteViews(getPackageName(),
				R.layout.notification_download);

		notification.contentView = contentView;
		mNotificationManager.notify(NOTIFY_ID, notification);
		startDownload();
	}

	private void startDownload() {
		canceled = false;
		new Thread(downloadRunnable).start();
	}

	private Handler mHandler = new Handler() {

		@Override
		public void handleMessage(Message msg) {
			super.handleMessage(msg);
			switch (msg.what) {
			case 0:// 下载完毕
					// 下载完毕
					// 取消通知
				SKNotificationManager.showNotification(DownloadService.this,
						getText(R.string.download_complete).toString(),
						getText(R.string.download_complete).toString(),12,true, 103
						);
				installApk();
				stopSelf();// 停掉服务自身
				break;
			case 1:
				int rate = msg.arg1;

				if (rate < 100) {
					RemoteViews contentview = notification.contentView;
					contentview.setTextViewText(R.id.tv_progress, rate + "%");
					contentview.setProgressBar(R.id.progressbar, 100, rate,
							false);
					mNotificationManager.notify(NOTIFY_ID, notification);
				} else {
					// 下载完毕后变换通知形式
					SKNotificationManager.showNotification(
							DownloadService.this,
							getText(R.string.download_complete).toString(),
							getText(R.string.download_complete).toString(),
							12, true,103);
					//
					stopSelf();// 停掉服务自身
				}

				break;
			default:
				break;
			}
		}

	};
	private int lastRate = 0;
	private Runnable downloadRunnable = new Runnable() {

		@Override
		public void run() {
			try {
				URL url = new URL(apkUrl);
                Log.e(tag, "hehe apkUrl:"+apkUrl);
				HttpURLConnection conn = (HttpURLConnection) url
						.openConnection();
				conn.connect();
				int length = conn.getContentLength();
				InputStream is = conn.getInputStream();

				File file = new File(savePath);
				if (!file.exists()) {
					file.mkdirs();
				}
				String apkFile = saveFileName;
				File ApkFile = new File(apkFile);
				FileOutputStream fos = new FileOutputStream(ApkFile);

				int count = 0;
				byte buf[] = new byte[1024];

				do {
					int numread = is.read(buf);
					count += numread;
					progress = (int) (((float) count / length) * 100);
					// 更新进度
					Message msg = mHandler.obtainMessage();
					msg.what = 1;
					msg.arg1 = progress;
					if (progress >= lastRate + 1) {
						mHandler.sendMessage(msg);
						lastRate = progress;

					}
					if (numread <= 0) {
						// 下载完成通知安装
						mHandler.sendEmptyMessage(0);
						// 下载完了，cancelled也要设置
						canceled = true;
						break;
					}
					fos.write(buf, 0, numread);
				} while (!canceled);// 点击取消就停止下载.

				fos.close();
				is.close();
			} catch (MalformedURLException e) {
				e.printStackTrace();
			} catch (IOException e) {
				e.printStackTrace();
			}

		}

	};

	/**
	 * 安装apk
	 * 
	 * @param url
	 */
	private void installApk() {
		File apkfile = new File(saveFileName);
		if (!apkfile.exists()) {
			return;
		}
		Intent i = new Intent(Intent.ACTION_VIEW);
		i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
		i.setDataAndType(Uri.parse("file://" + apkfile.toString()),
				"application/vnd.android.package-archive");
		startActivity(i);
	}

}
